<?php
//计算缩放后的高度
function resize($width,$height,&$new_width,&$new_height,$w=260,$h=260,$flag="1"){
    if ($width == 0 || $height == 0 || $w == 0) {
        error_log("width = $width, height = $height, w = $w");
        return;
    }
    switch($flag){
        case "1":
            if(($width / $height) >= ($w / $h)){
                if($width > $w){
                    $new_width=$w;
                    $new_height=ceil(($height*$w)/$width);
                }else{
                    $new_width=$width;
                    $new_height=$height;
                }
            }else{
                if($height > $h){
                    $new_height=$h;
                    $new_width=ceil(($width*$h)/$height);
                }else{
                	$new_width = $width;
                    $new_height= $height;
                }
            }
            break;
        case "2":
            if($width>$w){
                $new_height=ceil(($w/$width)*$height);
                $new_width=$w;
            }else{
                $new_width=$w;
                $new_height=$height;
            }
             break;
    }
}



function ZoomImgFileEx($userid,$filename,$scan_list,$added_water_mark_size){
    $userPath = get_user_picture_path($userid);
    $base="../user/".$userPath."/";
	if(!file_exists($base."/pic/".$filename) || getext($base."/pic/".$filename)=="unkown"){
		error_log($base."/pic/".$filename." or ".$base."/pic/".$filename." 不存在");
		return false;
	}

    $im=imagecreatefromjpeg($base."/pic/".$filename);
    if($im=="" || !$im) {
		error_log("创建图片".$base."/pic/".$filename." 句柄失败");
        return false;
    }
    //取得图片高度
    $height=imagesy($im);
    //取得图片宽度
    $width=imagesx($im);
    //新的宽度
    $new_width=0;
    //新的高度
    $new_height=0;
    //存放缩放里表中的宽度
    $arr_width=array();
    $arr_height=array();
    //存放缩放模斑
    $arr_tpl=array();
    //缩放后图片文件的路径
    $arr_file=array();
    //分析缩放列表
    for($v=0;$v<count($scan_list);$v++) {
        $path=$base."/".$scan_list[$v]."/";
        $p=explode("X",$scan_list[$v]);
        if(!file_exists($path.$scan_list[$v].".jpg")&&$p[0]!=0&&$p[1]!=0) {
            //创建空白模版
            $tmp_s=imagecreatetruecolor($p[0],$p[1]);
			if($tmp_s=="" || !tmp_s){
				error_log("创建空白模板失败");
				return false;
			}
            //创建空白模版
            $red =imagecolorallocate($tmp_s, 255, 255, 255);
            //设置摸班背景色
            imagefill($tmp_s, 0, 0, $red);
            imagejpeg($tmp_s,$path.$scan_list[$v].".jpg");
            imagedestroy($tmp_s);
            //修改文件属性
            chmod($path.$scan_list[$v].".jpg",0644);
        }
        $arr_width[]=$p[0];
        $arr_height[]=$p[1];
        $arr_tpl[]=$path.$scan_list[$v].".jpg";
        $arr_file[]=$path.$filename;
    }
    for($i=0;$i<count($arr_width);$i++){
        //用图片原始高度计算缩放后的高度和宽度
        if($arr_height[$i]=="0"){
            resize($width,$height,&$new_width,&$new_height,$arr_width[$i],$arr_height[$i],"2");
        }else{
            resize($width,$height,&$new_width,&$new_height,$arr_width[$i],$arr_height[$i]);
        }
        if($arr_width[$i] == $arr_height[$i] ){
            //计算缩放后图片的位置 保证缩放后图片是居中的
            if(($new_width == $arr_width[$i]) && ($new_height == $arr_height[$i])) {
                $x=0;
                $y=0;
            }else if(($new_width < $arr_width[$i]) && ($new_height < $arr_height[$i]) ){
                $x=ceil(($arr_width[$i]-$new_width)/2);
                $y=ceil(($arr_height[$i]-$new_height)/2);
            }else if(($new_width == $arr_width[$i]) && ($new_height < $arr_height[$i])){
                $x=0;
                $y=ceil(($arr_height[$i]-$new_height)/2);
            }else if(($new_width < $arr_width[$i]) && ($new_height == $arr_height[$i])){
                $x=ceil(($arr_width[$i]-$new_width)/2);
                $y=0;
            }
			if(!file_exists($arr_tpl[$i])){
				continue;
			}
            $imgs=imagecreatefromjpeg($arr_tpl[$i]);
			if($imgs=="" || !imgs){
				continue;
			}
            if(imagecopyresampled($imgs,$im,$x,$y,2,2,$new_width,$new_height,imagesx($im)-2,imagesy($im)-2)==FALSE) {
                //出错处理
				error_log("生成".$arr_width[$i]."X".$arr_width[$i]."图片失败");
				continue;
            }
        }else {
            if($width >= $arr_width[$i]){
                //创建空白模版
				if($new_width<0 || $new_height<0){
					continue;
				}
                $imgs=imagecreatetruecolor($new_width,$new_height);
                //创建空白模版
				if($imgs=="" || !imgs){
					continue;
				}
                $red =imagecolorallocate($imgs, 255, 255, 255);
                //设置摸班背景色
                imagefill($imgs, 0, 0, $red);
                if($width<$new_width) {
                    $x=ceil(($new_width-$width)/2);
                }else if($width>=$new_width){
                    $x=0;
                }
                if(imagecopyresampled($imgs,$im,$x,0,0,0,($new_width-2*$x),$new_height,$width,$height)==FALSE){
                    //出错处理
					error_log("生成".$new_width."X".$new_height."图片失败");
					continue;
                }
            }else {
                $imgs=imagecreatefromjpeg($base."/pic/".$filename);
            }
        }
        if(imagejpeg($imgs,$arr_file[$i])==FALSE){
			error_log("生成".$arr_file[$i]." 失败");           //出错处理
        }
        //修改文件属性
        chmod($arr_file[$i],0644);
        // 给560X0目录下的图片加水印
        if($arr_width[$i]=="560")
            imageWaterMark($arr_file[$i],9,SITE_ROOT."/images/watermark.png");
        if ($added_water_mark_size!="" && $arr_width[$i]==$added_water_mark_size) {
        	imageWaterMark($arr_file[$i],9,SITE_ROOT."/images/watermark.png");
        }
		if($imgs){
        	imagedestroy($imgs);
		}
    }
	if($im){
    	imagedestroy($im);
    }
	return true;
}

//处理上传图片
function ConversionToJpg($filename,$userid,$base="../static/user"){
    $tmp=explode(".",$filename);
    //取得文件名称
    $name=$tmp[0];
    //取得文件扩张名称
    $exc=strtolower($tmp[1]);
    $s_name="";  //固定路径
    $userPath = get_user_picture_path($userid);
    $base .= "/$userPath";
    //聘路径名
    $user_img=$base."/face/".$name.".jpg";
    //取得原始的文件名称
    $s_name=$base."/face/".$filename;
    //开始转化
    return ConversionToJpgEx($s_name,$user_img,$exc);
}

//获取图片的后缀
function getext($img){
    if(($imgInfo=@getimagesize($img))){
        switch($imgInfo[2]){
            case "1":
                return "gif";
                break;
            case "2":
                return "jpg";
                break;
            case "3":
                return "png";
                break;
            case "6":
                return "bmp";
                break;
            default:
                return "unkown";
        }
    }else{
        return  "unkown";
    }
}

function ConversionToJpgEx($s_name,$d_name,$exc){
    $im="";
	if(!file_exists($s_name)){
		error_log($s_name." 不存在");
		return "0";
	}
    switch($exc) {
        case "gif":
            if(($im=@imagecreatefromgif($s_name))!="" || ($im=@imagecreatefromstring(file_get_contents($s_name)))!="" || ($im=@imageToGDHandle($s_name))!=""){
	                if(imagejpeg($im,$d_name)==FALSE){
					error_log($d_name." 创建失败");
                    return "0";
                }
                chmod($d_name,0644);
            }
            break;
        case "jpg":
            if(($im=@imagecreatefromjpeg($s_name))!="" || ($im=@imagecreatefromstring(file_get_contents($s_name)))!="" || ($im=@imageToGDHandle($s_name))!="") {

                if(imagejpeg($im,$d_name)==FALSE) {
					error_log($d_name." 创建失败");
                    return "0";
                }
                chmod($d_name,0644);
            }
            break;
        case "png":
            if(($im=@imagecreatefrompng($s_name))!="" || ($im=@imagecreatefromstring(file_get_contents($s_name)))!="" || ($im=@imageToGDHandle($s_name))!="") {
                if(imagejpeg($im,$d_name)==FALSE) {
					error_log($d_name." 创建失败");
                    return "0";
                }
                chmod($d_name,0644);
            }
            break;
        case "bmp":
            if(($im=@imagecreatefrombmp($s_name))!="" || ($im=@imagecreatefromstring(file_get_contents($s_name)))!="" || ($im=@imageToGDHandle($s_name))!=""){
                if(imagejpeg($im,$d_name)==FALSE){
					error_log($d_name." 创建失败");
                    return "0";
                }
                chmod($d_name,0644);
            }
            break;
        default:
            return "0";
            break;
    }
    return "1";
}

/*********bmp文件转为jpg文件*******/

function ConvertBMP2GD($src, $dest = false){
    if(!($src_f = fopen($src, "rb"))) {
		error_log($src." 打开失败");
        return false;
    }
    if(!($dest_f = fopen($dest, "wb"))) {
		error_log($src." 打开失败");
        return false;
    }
    $header = unpack("vtype/Vsize/v2reserved/Voffset", fread($src_f, 14));
    $info = unpack("Vsize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vncolor/Vimportant", fread($src_f, 40));
    extract($info);
    extract($header);
    if($type != 0x4D42) { // signature "BM"
        return false;
    }
    $palette_size = $offset - 54;
    $ncolor = $palette_size / 4;
    $gd_header = "";
    // true-color vs. palette
    $gd_header .= ($palette_size == 0) ? "\xFF\xFE" : "\xFF\xFF";
    $gd_header .= pack("n2", $width, $height);
    $gd_header .= ($palette_size == 0) ? "\x01" : "\x00";
    if($palette_size) {
        $gd_header .= pack("n", $ncolor);
    }
    // no transparency
    $gd_header .= "\xFF\xFF\xFF\xFF";
    fwrite($dest_f, $gd_header);
    if($palette_size) {
        $palette = fread($src_f, $palette_size);
        $gd_palette = "";
        $j = 0;
        while($j < $palette_size) {
            $b = $palette{$j++};
            $g = $palette{$j++};
            $r = $palette{$j++};
            $a = $palette{$j++};
            $gd_palette .= "$r$g$b$a";
        }
        $gd_palette .= str_repeat("\x00\x00\x00\x00", 256 - $ncolor);
        fwrite($dest_f, $gd_palette);
    }
    $scan_line_size = (($bits * $width) + 7) >> 3;
    $scan_line_align = ($scan_line_size & 0x03) ? 4 - ($scan_line_size & 0x03) : 0;
    for($i = 0, $l = $height - 1; $i < $height; $i++, $l--) {
        // BMP stores scan lines starting from bottom
        fseek($src_f, $offset + (($scan_line_size + $scan_line_align) *$l));
        $scan_line = fread($src_f, $scan_line_size);
        if($bits == 24) {
            $gd_scan_line = "";
            $j = 0;
            while($j < $scan_line_size) {
                $b = $scan_line{$j++};
                $g = $scan_line{$j++};
                $r = $scan_line{$j++};
                $gd_scan_line .= "\x00$r$g$b";
            }
        } else if($bits == 8) {
            $gd_scan_line = $scan_line;
        }else if($bits == 4) {
            $gd_scan_line = "";
            $j = 0;
            while($j < $scan_line_size) {
                $byte = ord($scan_line{$j++});
                $p1 = chr($byte >> 4);
                $p2 = chr($byte & 0x0F);
                $gd_scan_line .= "$p1$p2";
            }
            $gd_scan_line = substr($gd_scan_line, 0, $width);
        } else if($bits == 1) {
            $gd_scan_line = "";
            $j = 0;
            while($j < $scan_line_size) {
                $byte = ord($scan_line{$j++});
                $p1 = chr((int) (($byte & 0x80) != 0));
                $p2 = chr((int) (($byte & 0x40) != 0));
                $p3 = chr((int) (($byte & 0x20) != 0));
                $p4 = chr((int) (($byte & 0x10) != 0));
                $p5 = chr((int) (($byte & 0x08) != 0));
                $p6 = chr((int) (($byte & 0x04) != 0));
                $p7 = chr((int) (($byte & 0x02) != 0));
                $p8 = chr((int) (($byte & 0x01) != 0));
                $gd_scan_line .= "$p1$p2$p3$p4$p5$p6$p7$p8";
            }
            $gd_scan_line = substr($gd_scan_line, 0, $width);
        }
        fwrite($dest_f, $gd_scan_line);
    }
    fclose($src_f);
    fclose($dest_f);
    chmod($src,0755);
    return true;
}
function imagecreatefrombmp($filename) {
    $tmp_name = tempnam("/tmp", "GD");
    if(ConvertBMP2GD($filename, $tmp_name)) {
        $img = imagecreatefromgd($tmp_name);
        unlink($tmp_name);
        return $img;
    }
    return "";
}

function imageToGDHandle($filename){
    try {
        $imgick=new Imagick;
        $imgick->readImage($filename);
        $tmp_name = tempnam("/tmp", "GD");
        if($imgick->setImageFormat("JPEG"))  {
            $imgick->writeimage($tmp_name);
            $imgick->destroy();
            $im=imagecreatefromjpeg($tmp_name);
            @unlink($tmp_name);
            return $im;
        }else {
			error_log($filename." 打开失败");
            return "";
        }
        return $im;
    }catch(Exception $ex) {
		error_log("异常:".$ex->getmessage());
        return "";
    }
}

////////

// $added_water_mark_size:除了默认的560*x尺寸的图片加水印外,还需要给哪个尺寸的加水印

function CreateAllSizePhoto($filename,$userid,$added_water_mark_size=""){
    //转换上传图片
    if(ConversionToJpg($filename,$userid)=="1"){
        //取得生成的尺寸列表
        global $G_SCAN_LIST;
        //所放图片
        return ZoomImgFile($filename,$userid,$G_SCAN_LIST,$added_water_mark_size);
    }else{
        return false;
    }
}

//所放图片

function ZoomImgFile($filename,$userid,$scan_list,$added_water_mark_size=""){
    $tmp=explode(".",$filename);
    //取得文件名称
    $img_name=$tmp[0].".jpg";
    //开始所放
    return ZoomImgFileEx($userid,$img_name,$scan_list,$added_water_mark_size);
}
/*

坐标转换

*/

function CoordinateTransToSmall($width,$height,$width1,$height1,$x,$y){
    $new_width=0;
    $new_height=0;
    resize($width,$height,$new_width,$new_height,$width1,$height1);
    $newx=ceil(($new_width/$width)*$x);
    $newy=ceil(($new_height/$height)*$y);
    if(($new_width == $width1) && ($new_height == $height1)) {
        $x=0;
        $y=0;
    }else if(($new_width < $width1) && ($new_height < $height1) ) {
        $x=ceil(($width1-$new_width)/2);
        $y=ceil(($height1-$new_height)/2);
    } else if(($new_width == $width1) && ($new_height < $height1)) {
        $x=0;
        $y=ceil(($height1-$new_height)/2);
    }else if(($new_width < $width1) && ($new_height == $height1)) {
        $x=ceil(($width1-$new_width)/2);
        $y=0;
    }
    $newx=$newx+$x;
    $newy=$newy+$y;
    return array("x"=>$newx,"y"=>$newy);
}



/**

 * Enter description here...

 *

 * @param unknown_type $width

 * @param unknown_type $height

 * @param unknown_type $width1

 * @param unknown_type $height1

 * @param unknown_type $x

 * @param unknown_type $y

 * @return unknown

 */

function CoordinateTransToBig($width,$height,$width1,$height1,$x1,$y1){
    $new_width=0;
    $new_height=0;
    resize($width,$height,$new_width,$new_height,$width1,$height1);
    if(($new_width == $width1) && ($new_height == $height1)) {
        $x=0;
        $y=0;
    } else if(($new_width < $width1) && ($new_height < $height1) ){
        $x=ceil(($width1-$new_width)/2);
        $y=ceil(($height1-$new_height)/2);
    } else if(($new_width == $width1) && ($new_height < $height1)){
        $x=0;
        $y=ceil(($height1-$new_height)/2);
    } else if(($new_width < $width1) && ($new_height == $height1)){
        $x=ceil(($width1-$new_width)/2);
        $y=0;
    }
    $x1=$x1-$x;
    $y1=$y1-$y;
    $newx=($width/$new_width)*$x1;
    $newy=($height/$new_height)*$y1;
    return array("x"=>$newx,"y"=>$newy);
}


function create_cuttom_img($width,$height,$img,$generate_newfile_flag=true,$sameext=false,$ifborder=true){
    //$im=imagecreatefromjpeg($img);
	if(!file_exists($img)){
		error_log("文件不存在");
		return "0";
	}
	$array=explode("/",$img);
	if($generate_newfile_flag)
		$array[count($array)-1]=$width."X".$height.$array[count($array)-1]; 
	$newfile=implode("/",$array);
    $imgsize = getimagesize($img);
    if ($imgsize[2]==1) {
        $im=imagecreatefromgif($img);
    } elseif($imgsize[2]==2) {
        $im=imagecreatefromjpeg($img);
    } elseif($imgsize[2]==3) {
        $im=imagecreatefrompng($img);
    } elseif($imgsize[2]==6) {
        $im=imagecreatefrombmp($img);
    }else{
		error_log("文件格式不正确");
		return "0";
	}
    if($im!="") {
        $owidth=imagesx($im);
        $oheight=imagesy($im);
        $new_width=0;
        $new_height=0;
        $x=0;
        $y=0;
        $fixx=0;
        $fixy=0;
        if($ifborder==false && $owidth<$width && $oheight<$height){
			$new_height=$height=$owidth;
			$new_width=$width=$owidth;
        }else{
	        resize($owidth,$oheight,&$new_width,&$new_height,$width,$height);
	        $fixx=2;
        	$fixy=2;
        }
    	//计算缩放后图片的位置 保证缩放后图片是居中的
    	if(($new_width == $width) && ($new_height == $height)){
    		$x=0;
    		$y=0;
    	}else if(($new_width < $width) && ($new_height < $height) )  {
    		$x=ceil(($width-$new_width)/2);
    		$y=ceil(($height-$new_height)/2);
    	} else if(($new_width == $width) && ($new_height < $height)) {
    		$x=0;
    		$y=ceil(($height-$new_height)/2);
    	}else if(($new_width < $width) && ($new_height == $height))  {
    		$x=ceil(($width-$new_width)/2);
    		$y=0;
    	}
        $imgs=imagecreatetruecolor($width,$height);
        if($imgs=="" || !$imgs){
        	error_log("创建空白图片出错");
        	return "0";
        }
        //创建空白模版
        $red = imagecolorallocate($imgs, 255, 255, 255);
        //设置摸班背景色
        imagefill($imgs, 0, 0, $red);
        if(imagecopyresampled($imgs,$im,$x,$y,$fixx,$fixy,$new_width,$new_height,imagesx($im)-$fixx,imagesy($im)-$fixy)==FALSE){
        	//出错处理
        	error_log("图片缩放失败".$new_width."X".$new_height);
        	return "0";
        }
        if($sameext==false){
	    if(imagejpeg($imgs,$newfile,100)==FALSE){
	            //出错处理
				error_log("生成图片失败");
	            return "0";
	        }
       }else{       		
			if ($imgsize[2]==1) {
				if(imagegif($imgs,$newfile)==FALSE){
					//出错处理
					error_log("生成图片失败");
					return "0";
				}
			} elseif($imgsize[2]==2) {
				if(imagejpeg($imgs,$newfile)==FALSE){
					//出错处理
					error_log("生成图片失败");
					return "0";
				}
			} elseif($imgsize[2]==3) {
				if(imagepng($imgs,$newfile)==FALSE){
					//出错处理
					error_log("生成图片失败");
					return "0";
				}
			} 
       }
        //修改文件属性
        chmod($newfile,0755);
        imagedestroy($imgs);
        imagedestroy($im);
        return $newfile;
    }else{
		error_log("取得图片句柄失败 ".$img);
        return "0";
    }
}




/**

* 删除所有规格的用户的图片

*

* @param $userid 用户ID号

* @param $photoname 图片名

* @param $pixext 图片后缀名,默认为jpg,注意:值不带.

*/

function com_del_user_photo($userid,$photoname,$picext="jpg",$where="") {
    // 删除pic下的图片
    $userPath = get_user_picture_path($userid);
    if(file_exists("../user/".$userPath."/pic/".$photoname)) {
        @unlink("../user/".$userPath."/pic/".$photoname);
    }
    // 删除base下的图片,因为base下的图片类型不全是jpg,所以要通过$ext参数进行处理
    $tmp1 = str_replace("jpg",$picext,"../user/".$userPath."/base/".$photoname);
    if(file_exists($tmp1)){
        @unlink($tmp1);
    }

    global $G_SCAN_LIST;
    if($where == "searchFriend" || $where == "searchface"){
    	for($s=0;$s<count($G_SCAN_LIST);$s++) {
	        if(file_exists("../user/".$userPath."/".$G_SCAN_LIST[$s]."/".$photoname) && $G_SCAN_LIST[$s]!="60X60" && $G_SCAN_LIST[$s]!="120X120" && $G_SCAN_LIST[$s]!="300X300") {
				  @unlink("../user/".$userPath."/".$G_SCAN_LIST[$s]."/".$photoname);
	        }
	    }
    }else{
	    for($s=0;$s<count($G_SCAN_LIST);$s++) {
	        if(file_exists("../user/".$userPath."/".$G_SCAN_LIST[$s]."/".$photoname) && $G_SCAN_LIST[$s]!="60X60") {
	            @unlink("../user/".$userPath."/".$G_SCAN_LIST[$s]."/".$photoname);
	        }
   		}
    }
}




function sendShareSearchFaceResult($photoname,$uid,$mails,$bodytext){
	$mail = new PHPMailer();
    $mail->CharSet = "UTF-8"; // 设置编码
	$rnd=rand(1,1000);
    $mail->From = "fk".$rnd."@facekoo.com"; //设置发送人的邮件
    $mail->FromName ='FaceKoo';//设置邮件标题
    $mail->AddAddress($mails,"facekoo");
    $mail->WordWrap = 50;
    $mail->ContentType='text/html';
    $userPath = get_user_picture_path($uid);
    $mail->AddEmbeddedImage("../user/".$userPath."/base/".$photoname,"cid_image1","image1","base64","image/jpeg");
    $mail->Subject = $bodytext;//设置邮件主体
    $mail->Body ="<html><body><p style='font-weight:bold;font-size:14px;color:bule;'>".$bodytext."</p><a href='www.facekoo.com'><img src='cid:cid_image1' border=0></a></body></html>\n";

    if(!$mail->Send()){
        return 0;
    }
    return 1;
}



//创建用户要分享的给好友的图片

function show_result_pic($data){
    $base_name=$data['base_name'];
    $font_path=$data['font_path'];
	if(!file_exists($base_name)){
		echo "pic missing";
		return false;
	}
    $im=@imagecreatefromjpeg($base_name);
	if($im=="" || !$im){
		echo "img create error";
		return false;
	}
    for($i=0;$i<count($data['pic']);$i++) {
        //画图片
		if(!file_exists($data['pic'][$i]['pic_path'])){
			return false;
		}
        $im1=@imagecreatefromjpeg($data['pic'][$i]['pic_path']);
		if($im1=="" || !im1){
			return false;
		}
        $width=@imagesx($im1);
        $height=@imagesy($im1);
        $new_width=0;
        $new_height=0;
        $w=$data['pic'][$i]['size'];
        resize($width,$height,$new_width,$new_height,$w,$w);
        $x=$data['pic'][$i]['px'];
        $y=$data['pic'][$i]['py'];
        $font_size=$data['font_size'][$i];
        $font_path=	$data['font_path'][$i];
        if(@imagecopyresampled($im,$im1,$x,$y,0,0,$new_width,$new_height,imagesx($im1),imagesy($im1))==FALSE){
            return fasle;
        }
        if(isset($data['pic'][$i]['pic_main'])){
            $color=@imagecolorallocate($im,0x00,0x00,0x00);
            $x=$data['font_name'][$i]['fx'];
            $y=$data['font_name'][$i]['fy'];
            $output_msg=$data['font_name'][$i]['msg'];
            //imagettftext($im,$font_size,0,$x,$y+13,$color,$font_path,$outpupt_msg);
            $len=220;
            //特殊处理
            $output_msg_array=explode("<>",$output_msg);
            $linecount=count($output_msg_array);
            for($tleng=0;$tleng<$linecount;$tleng++) {
                $boxs=@imagettfbbox($font_size,0,$font_path,$output_msg_array[$tleng]);
                $x=$x+($boxs[2]-$boxs[0]);
                $word_height=$boxs[1]-$boxs[5];
                @imagettftext($im,$font_size,0,$x,$y,$color,$font_path,$output_msg_array[$tleng]);
                $linelength=$x-$data['font_name'][$i]['fx'];
                if($linelength>220 || $linelength==220)   {
                    $x=$data['font_name'][$i]['fx'];
                    $y=$y+$word_height+8;
                }
            }
        } else {
            //画名字
            $color=@imagecolorallocate($im,0x00,0x00,0x00);
            $x=$data['font_name'][$i]['fx'];
            $y=$data['font_name'][$i]['fy'];
            $star_name=$data['font_name'][$i]['msg'];
            //计算位置是名字居中
            $boxs=@imagettfbbox($font_size,0,$font_path,$star_name);
            if(($boxs[4]-$boxs[6])>$w){
                $star_name=showShort($star_name,7);
                $boxs=@imagettfbbox($font_size,0,$font_path,$star_name);
            }
            $px=ceil(($boxs[4]-$boxs[6])/2);
            $x=$data['pic'][$i]['px']+ceil($w/2)-$px;
            @imagettftext($im,$font_size,0,$x,$y+13,$color,$font_path,$star_name);     //画分数
            $color=@imagecolorallocate($im,0x00,0x00,0x00);
            $x=$data['font_score'][$i]['fx'];
            $y=$data['font_score'][$i]['fy'];
            $msg="相似度:";
            $box=@imagettftext($im,$font_size,0,$x,$y+13,$color,$font_path,$msg);
            $x=$box[4];
            $y=$box[5];
            $color=@imagecolorallocate($im,0xff,0x00,0x00);
            $msg=$data['font_score'][$i]['msg'];
            @imagettftext($im,$font_size,0,$x+5,$y+13,$color,$font_path,$msg);
        }
        @imagedestroy($im1);
    }

    //画网站信息
    $color=@imagecolorallocate($im,2,0,251);
    $x=$data['website'][0]['fx'];
    $y=$data['website'][0]['fy'];
    $msg=$data['website'][0]['msg'];
    $font_path=$data['website'][0]['font_path'];
    $font_size=$data['website'][0]['font_size'];
    @imagettftext($im,$font_size,0,$x,$y+10,$color,$font_path,$msg);
    @imagejpeg($im);//输出图片
    @imagedestroy($im);//释放资源
}



/*

功能：根据坐标进行图片切割

userid :图片的所有者的id

picname :要进行切割的原始图片

x0 y0 x1 y1  为要切割的区域坐标

*/

function CuttingJpg($userid,$pic_name,$x0,$y0,$x1,$y1,$basepath="../user/"){
	if(!file_exists($pic_name))
		return "";
    $im=@imagecreatefromjpeg($pic_name);
	if(!$im || $im=="" || $im==FALSE)
		return "";
    $width=@imagesx($im);
    $height=@imagesy($im);
    $new_width=0;
    $new_height=0;
    $height1=300;
    $width1=300;
    resize($width,$height,$new_width,$new_height,$width1,$height1);
    if($new_width >0 && $new_height > 0){
        if(($new_width == $width1) && ($new_height == $height1)) {
            $x=0;
            $y=0;
        }else if(($new_width < $width1) && ($new_height < $height1) ){
            $x=ceil(($width1-$new_width)/2);
            $y=ceil(($height1-$new_height)/2);
        }else if(($new_width == $width1) && ($new_height < $height1)) {
            $x=0;
            $y=ceil(($height1-$new_height)/2);
        } else if(($new_width < $width1) && ($new_height == $height1)){
            $x=ceil(($width1-$new_width)/2);
            $y=0;
        }
    }
    $newx0=$x0-$x;
    $newy0=$y0-$y;
    $newx1=$x1-$x;
    $newy1=$y1-$y;
    $scanx=($width/$new_width);
    $scany=($height/$new_height);
    $newx0=ceil($scanx*$newx0);
    $newy0=ceil($scany*$newy0);
    $newx1=ceil($scanx*$newx1);
    $newy1=ceil($scany*$newy1);
    $pic_w=$newx1-$newx0;
    $pic_h=$newy1-$newy0;
	if(!is_numeric($pic_w) || !is_numeric($pic_h) || $pic_w<0 || $pic_h<0){
		return "";
	}
    $imgs=@imagecreatetruecolor($pic_w,$pic_h);
    if ($imgs=="" || !imgs) {
        error_log("imagecreatetruecolor returns error: x0:$x0 y0:$y0 x1:$x1 y1:$y1");
        return "";
    }
    //创建空白模版
    $red = @imagecolorallocate($imgs, 255, 255, 255);
    //设置摸班背景色
    @imagefill($imgs, 0, 0, $red);
    if(@imagecopyresampled($imgs,$im,0,0,$newx0,$newy0,$pic_w,$pic_h,$pic_w,$pic_h)==FALSE) {
    	error_log("缩放图片失败");
    	@imagedestroy($im);
        return "";
    } else {
        $temArray=explode("/",$pic_name);
        $userPath = get_user_picture_path($userid);
        $temp_path=$basepath.$userPath."/temp/cut".array_pop($temArray);
        @imagejpeg($imgs,$temp_path);
        chmod($temp_path,0755);
        @imagedestroy($imgs);
        @imagedestroy($im);
        return $temp_path;
    }
}

function move_user_photo($userid,$sourcefile,$sourcePath,$destPath) {
    global $G_SCAN_LIST;    
    array_push($G_SCAN_LIST,"pic");
    array_push($G_SCAN_LIST,"base");
    if($destPath=="user") {
        $destPath .= "/".get_user_picture_path($userid);
        $desta = SITE_ROOT."/".$destPath;
    } else {
        $desta = SITE_ROOT."/".$destPath."/".$userid;
    }
    if(!file_exists($desta)) {
        mkdir($desta);
        chmod($desta,0755);
    }

    for($s=0;$s<count($G_SCAN_LIST);$s++) {
        $dest = $desta. "/".$G_SCAN_LIST[$s]."/"; 
        if(!file_exists($dest) && $destPath!="user" ) {
            mkdir($dest);
            chmod($dest,0755);
        }
        if($sourcePath=="user")
            $source = SITE_ROOT."/".$sourcePath."/".get_user_picture_path($userid)."/".$G_SCAN_LIST
[$s]."/".$sourcefile;
      else 
            $source = SITE_ROOT."/".$sourcePath."/".$userid."/".$G_SCAN_LIST[$s]."/".$sourcefile;
        $dest = $dest.$sourcefile;
        if(file_exists($source) && !copy($source,$dest)) {
            $errfile = fopen(SITE_ROOT."/modules/admin/move_file_err.log","a+");
            fwrite($errfile,"MOVE: ".$source."==>".$dest.":failed [".date("Y-m-d H:i:s")."]\r\n");
            fclose($errfile);
        }
        if(file_exists($source) && !unlink($source)) {
            $errfile = fopen(SITE_ROOT."/modules/admin/move_file_err.log","a+");
            fwrite($errfile,"DELETE: ".$source.":failed [".date("Y-m-d H:i:s")."]\r\n");
            fclose($errfile);
       }
    }
}

/* 

* 功能：PHP图片水印 (水印支持图片或文字) 

* 参数： 

*      $groundImage    背景图片，即需要加水印的图片，暂只支持GIF,JPG,PNG格式； 

*      $waterPos       水印位置，有10种状态，0为随机位置； 

*                      1为顶端居左，2为顶端居中，3为顶端居右； 

*                      4为中部居左，5为中部居中，6为中部居右； 

*                      7为底端居左，8为底端居中，9为底端居右； 

*      $waterImage     图片水印，即作为水印的图片，暂只支持GIF,JPG,PNG格式； 

*      $waterText      文字水印，即把文字作为为水印，支持ASCII码，不支持中文； 

*      $textFont       文字大小，值为1、2、3、4或5，默认为5； 

*      $textColor      文字颜色，值为十六进制颜色值，默认为#FF0000(红色)； 

* 

* 注意：Support GD 2.0，Support FreeType、GIF Read、GIF Create、JPG 、PNG 

*      $waterImage 和 $waterText 最好不要同时使用，选其中之一即可，优先使用 $waterImage。 

*      当$waterImage有效时，参数$waterString、$stringFont、$stringColor均不生效。 

*      加水印后的图片的文件名和 $groundImage 一样。 

*/ 
function imageWaterMark($groundImage,$waterPos=0,$waterImage="",$waterText="", $textFont=5,$textColor="#FF0000") {
	$isWaterImage = FALSE; 
    $formatMsg = "暂不支持该文件格式，请用图片处理软件将图片转换为GIF、JPG、PNG格式。"; 
     //读取水印文件 
    if(!empty($waterImage) && file_exists($waterImage)) { 
        $isWaterImage = TRUE; 
        $water_info = getimagesize($waterImage); 
        $water_w    = $water_info[0];   //取得水印图片的宽 
        $water_h    = $water_info[1];   //取得水印图片的高 
        switch($water_info[2])  {   //取得水印图片的格式  
            case 1:$water_im = imagecreatefromgif($waterImage);break; 
            case 2:$water_im = imagecreatefromjpeg($waterImage);break; 
            case 3:$water_im = imagecreatefrompng($waterImage);break; 
            default:die($formatMsg); 
        } 
    }   //读取背景图片 
    if(!empty($groundImage) && file_exists($groundImage)) { 
        $ground_info = getimagesize($groundImage); 
        $ground_w    = $ground_info[0];//取得背景图片的宽 
        $ground_h    = $ground_info[1];//取得背景图片的高 
        switch($ground_info[2]) {   //取得背景图片的格式  
            case 1:$ground_im = imagecreatefromgif($groundImage);break; 
            case 2:$ground_im = imagecreatefromjpeg($groundImage);break; 
            case 3:$ground_im = imagecreatefrompng($groundImage);break; 
            default:die($formatMsg); 
        } 
    } else { 
        die("需要加水印的图片不存在！"); 
    } 
    //水印位置 

    if($isWaterImage) { //图片水印  
        $w = $water_w; 
        $h = $water_h; 
        $label = "图片的";  
     } else {  //文字水印 
        $temp = imagettfbbox(ceil($textFont*2.5),0,"/usr/local/psa/home/vhosts/tujidi.cn/httpdocs/inc/simsun.ttc",$waterText);//取得使用 TrueType 字体的文本的范围 
        $w = $temp[2] - $temp[6]; 
        $h = $temp[3] - $temp[7]; 
        unset($temp); 
        $label = "文字区域";
      } 
    if( ($ground_w<$w) || ($ground_h<$h) ) {
    	return; 
    } 
    switch($waterPos) { 
        case 0://随机 
            $posX = rand(0,($ground_w - $w)); 
            $posY = rand(0,($ground_h - $h));  
            break; 
        case 1://1为顶端居左 
            $posX = 0; 
            $posY = 0; 
            break; 
        case 2://2为顶端居中 
            $posX = ($ground_w - $w) / 2; 
            $posY = 0; 
            break; 
        case 3://3为顶端居右 
            $posX = $ground_w - $w; 
            $posY = 0; 
            break; 
        case 4://4为中部居左 
            $posX = 0; 
            $posY = ($ground_h - $h) / 2; 
            break; 
        case 5://5为中部居中 
            $posX = ($ground_w - $w) / 2; 
            $posY = ($ground_h - $h) / 2; 
            break; 
        case 6://6为中部居右 
            $posX = $ground_w - $w; 
            $posY = ($ground_h - $h) / 2; 
            break; 
        case 7://7为底端居左 
            $posX = 0; 
            $posY = $ground_h - $h; 
            break; 
        case 8://8为底端居中 
            $posX = ($ground_w - $w) / 2; 
            $posY = $ground_h - $h; 
            break; 
        case 9://9为底端居右 
            $posX = $ground_w - $w; 
            $posY = $ground_h - $h; 
            break; 
        default://随机 
            $posX = rand(0,($ground_w - $w)); 
            $posY = rand(0,($ground_h - $h)); 
            break;    

    }     //设定图像的混色模式 
   imagealphablending($ground_im, true); 
    if($isWaterImage) { //图片水印  
     	imagecopy($ground_im, $water_im, $posX, $posY, 0, 0, $water_w,$water_h);//拷贝水印到目标文件  
  } else {//文字水印
    	if( !empty($textColor) && (strlen($textColor)==7) ) { 
            $R = hexdec(substr($textColor,1,2)); 
            $G = hexdec(substr($textColor,3,2)); 
            $B = hexdec(substr($textColor,5)); 
        } else { 
            die("水印文字颜色格式不正确！"); 
        } 
        $fnt = "/usr/local/psa/home/vhosts/tujidi.cn/httpdocs/inc/simsun.ttc";
        $white = imagecolorallocate($ground_im, 255, 255, 255);
        $txt_bg = imagecreatefrompng("../images/txt_bg.png");
        //imagecopy($ground_im, $txt_bg, 0, 180, 0, 0, 300,25);
        //imagettftext( $ground_im,"12",0,$posX,$posY,$white,$fnt,$waterText);
    } 
    //生成水印后的图片 
    @unlink($groundImage); 
    switch($ground_info[2]) {//取得背景图片的格式 
        case 1:imagegif($ground_im,$groundImage);break; 
        case 2:imagejpeg($ground_im,$groundImage);break; 
        case 3:imagepng($ground_im,$groundImage);break; 
        default:die($errorMsg); 
    } 
    //释放内存 
    if(isset($water_info)) unset($water_info); 
    if(isset($water_im)) imagedestroy($water_im); 
    if(isset($txt_bg)) imagedestroy($txt_bg);   
    unset($ground_info); 
    imagedestroy($ground_im); 
}

function setPhotoSpec($id,$specflag,$remark="",$photo_table,$admin_id="") {
	    global $mysqli_write,$mysqli_read;
	    global $private_pic;
	    if($photo_table=='fk_showcase_photos'){
	       $res = $mysqli_read->query("SELECT a.goods_id, a.user_id as ofuser, p.photoname, p.specflag, p.specremark FROM fk_showcase_photos p, fk_showcase_goods a WHERE p.case_id = a.goods_id AND p.photoname IN $id"); 
	    } else {
	       $res = $mysqli_read->query("select id,photoname,ofuser,specflag from ".$photo_table." where id in $id");
	    }
		while($row = $res->fetch_array(MYSQLI_ASSOC)) {
        	if($row['specflag']==$specflag)
        	  return 0;  
			
        	if($specflag=="2") {
        	    if ($photo_table!="fk_showcase_photos") {  

        			// 判断是否为形象照，如果是，在拒绝通过时要进行处理(晒品不能设为形象照,所以排除在外)
        			$res1 = $mysqli_read->query("select mainphoto from fk_users where id='".$row['ofuser']."'");
        			$row1= $res1->fetch_array(MYSQLI_ASSOC);
        			if($row1['mainphoto']==$row['photoname']) {
        				$mysqli_write->query("update fk_users set mainphoto='' where id='".$row['ofuser']."'");
        			}
        	    }
                if($photo_table=="fk_myphotos") {
        			// 如果是相册,还需要判断是否为相册封面，如果是，在拒绝通过时要进行处理
        			$res2 = $mysqli_read->query("select photoname,ofalbum,ofuser from fk_myphotos where id='".$row['id']."'");
    				$row2 = $res2->fetch_array(MYSQLI_ASSOC);
    				$res3 = $mysqli_read->query("select cover from fk_album where albumid='".$row2['ofalbum']."' and ofuser='".$row2['ofuser']."'");
    				$row3= $res3->fetch_array(MYSQLI_ASSOC);
    				if($row3['cover']==$row1['photoname']) {
    					$mysqli_write->query("update fk_album set cover='',lockerID='$admin_id' where albumid='".$row2['ofalbum']."' and ofuser='".$row2['ofuser']."'");
    					//$mysqli_write->query("update fk_album set cover='' where albumid='".$row2['ofalbum']."' and ofuser='".$row2['ofuser']."'");
    				}
                } elseif ($photo_table=="fk_showcase_photos") {
        			// 如果是晒柜,还需要判断是否为晒品的封面，如果是，在拒绝通过时要进行处理
    				$res2 = $mysqli_read->query("select photoname,goods_id from fk_showcase_goods where goods_id='".$row['goods_id']."'"); 
    				$row2 = $res2->fetch_array(MYSQLI_ASSOC);  
    				if ( $row2['photoname'] == $row['photoname'] ) {      // 是封面
    				    $res3 = $mysqli_read->query("select photoname from fk_showcase_photos where case_id='".$row['goods_id']."' AND ifchecked <>'2' and ifchecked <> '3' and photoname<>'".$row2['photoname']."'");

    				    if($res3->num_rows>0) {
    				        $row3 = $res3->fetch_array(MYSQLI_ASSOC);
    				        $mysqli_write->query("UPDATE fk_showcase_goods SET photoname='".$row3['photoname']."',lockerID='$admin_id' WHERE goods_id='". $row['goods_id'] ."'");
    				        //$mysqli_write->query("UPDATE fk_showcase_goods SET photoname='".$row3['photoname']."' WHERE goods_id='". $row['goods_id'] ."'");
						  } else {
    				        // 所有该晒品的图片都被锁定了,则直接将该晒品锁定
    				        $mysqli_write->query("UPDATE fk_showcase_goods SET ifchecked='2',lockerID='$admin_id' WHERE goods_id='". $row['goods_id'] ."'");
    				        //$mysqli_write->query("UPDATE fk_showcase_goods SET iflock='1' WHERE goods_id='". $row['goods_id'] ."'");
    				        $mysqli_write->query("update fk_useraction_2 set hide='1' where source_id='". $row['goods_id'] ."' and elementid='28'");
    				    }
    				}
                }
    		}
        	if ($specflag=="2") {      // 拒绝,则将该图片移动到私有目录中
        	  move_user_photo($row['ofuser'],$row['photoname'],"user",$private_pic);
        	  if($photo_table=="fk_searchface_photo" || $photo_table=="fk_searchfriend_photo") {
        	  	// 如果是搜星或者搜友,则要将魔镜秀贴纸所生成的照片也搬到私有目录中
        	      move_user_photo($row['ofuser'],$row['ofuser']."_".$row['photoname']."_1","user",$private_pic);
        	      move_user_photo($row['ofuser'],$row['ofuser']."_".$row['photoname']."_2","user",$private_pic);
        	      move_user_photo($row['ofuser'],$row['ofuser']."_".$row['photoname']."_3","user",$private_pic);
        	      move_user_photo($row['ofuser'],$row['ofuser']."_".$row['photoname']."_4","user",$private_pic);
        	  }
        	} elseif ($specflag=="1" && $row['specflag']=="2") {
        	  move_user_photo($row['ofuser'],$row['photoname'],$private_pic,"user");
        	  if($photo_table=="fk_searchface_photo" || $photo_table=="fk_searchfriend_photo" ) {
        	  	// 如果是搜脸,则要将魔镜秀贴纸所生成的照片般回来,已正常显示
        	     move_user_photo($row['ofuser'],$row['ofuser']."_".$row['photoname']."_1",$private_pic,"user");
        	     move_user_photo($row['ofuser'],$row['ofuser']."_".$row['photoname']."_2",$private_pic,"user");
        	     move_user_photo($row['ofuser'],$row['ofuser']."_".$row['photoname']."_3",$private_pic,"user");
        	     move_user_photo($row['ofuser'],$row['ofuser']."_".$row['photoname']."_4",$private_pic,"user");
        	  } elseif ($photo_table=="fk_showcase_photos") {
        	      $mysqli_write->query("UPDATE fk_showcase_goods SET iflock='0',ifchecked='$ifchecked',lockerID='$admin_id' WHERE goods_id='". $row['goods_id'] ."'");
				  //$mysqli_write->query("UPDATE fk_showcase_goods SET iflock='0' WHERE goods_id='". $row['goods_id'] ."'");
        	      $mysqli_write->query("update fk_useraction_2 set hide='0' where source_id='". $row['goods_id'] ."' and elementid='28'");
        	  }
        	}
		}
		if($photo_table=='fk_showcase_photos'){
		    $sqlstr = "UPDATE ".$photo_table." SET specflag='$specflag',specremark= '$remark',lockerID='$admin_id',ifchecked='$specflag',reason='".$mysqli_write->real_escape_string($_REQUEST['reason'])."' WHERE photoname in $id";
			//$sqlstr = "UPDATE ".$photo_table." SET specflag='$specflag',specremark= '$remark' WHERE photoname in $id";
		}else{
            $sqlstr = "UPDATE ".$photo_table." SET specflag='$specflag',specremark= '$remark',lockerID='$admin_id',ifchecked='$specflag',reason='".$mysqli_write->real_escape_string($_REQUEST['reason'])."' WHERE id in $id";
			//$sqlstr = "UPDATE ".$photo_table." SET specflag='$specflag',specremark= '$remark' WHERE id in $id";
		}
        $mysqli_write->query($sqlstr);
    	return $mysqli_write->errno;
	}
function rotate_image_on_exif($filename) {
    $exif = exif_read_data($filename);
    if ($exif && ($ort = $exif['IFD0']['Orientation'])) {
        $image = new Imagick($filename);
        switch($ort) {
        case 1: // nothing
            break;
        case 2: // horizontal flip
            $image->flipImage($public,1);
            break;
        case 3: // 180 rotate left
            $image->rotateImage($public,180);
            break;
        case 4: // vertical flip
            $image->flipImage($public,2);
            break;
        case 5: // vertical flip + 90 rotate right
            $image->flipImage($public, 2);
            $image->rotateImage($public, -90);
            break; 
        case 6: // 90 rotate right
            $image->rotateImage($public, -90);
            break;
        case 7: // horizontal flip + 90 rotate right
            $image->flipImage($public,1);   
            $image->rotateImage($public, -90);
            break;
        case 8:    // 90 rotate left
            $image->rotateImage($public, 90);
            break;
        }
        $image->writeImage($filename);
        $image->clear();
        $image->destroy();
    }
}

function _scan($userid,$filename,$scan_list,$added_water_mark_size){
	error_log("function _scan use");
	return ZoomImgFileEx($userid,$filename,$scan_list,$added_water_mark_size);
}

function scan_img($filename,$userid,$scan_list,$added_water_mark_size=""){
	error_log("function scan_img use");
	return ZoomImgFile($filename,$userid,$scan_list,$added_water_mark_size="");
}

function do_photo_upload($filename,$userid,$added_water_mark_size="") {
	error_log("function do_photo_upload use");
	return CreateAllSizePhoto($filename,$userid,$added_water_mark_size="");
}

function a_to_b($width,$height,$width1,$height1,$x,$y){ 
	error_log("function a_to_b use");
	return CoordinateTransToSmall($width,$height,$width1,$height1,$x,$y);
}

function b_to_a($width,$height,$width1,$height1,$x1,$y1){ 
	 error_log("function b_to_a use");
	 return CoordinateTransToBig($width,$height,$width1,$height1,$x1,$y1);
}

function trans_img($filename,$userid,$base="../user"){
	error_log("function trans_file use");
	return ConversionToJpg($filename,$userid,$base="../user");
}

function cut_pic($userid,$pic_name,$x0,$y0,$x1,$y1){
	error_log("function cut_pic use");
 	return CuttingJpg($userid,$pic_name,$x0,$y0,$x1,$y1);
 }
 
 function tran_file_to_jpg($s_name,$d_name,$exc){
	error_log("function tran_file_to_jpg use");
 	return ConversionToJpgEx($s_name,$d_name,$exc);
 }
?>